package com.example.demo.practice.devices;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.demo.practice.R;
import com.example.demo.practice.innerclass.IBaseActivity;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;


public class InspectionQuestion extends IBaseActivity {
    private static final String FILE_PATH = "/sdcard/sysvideocamera.3gp";
    private static final String TAG="main";

    private static int REQUEST_THUMBNAIL = 1;// 请求缩略图信号标识

    private int REQUEST_CODE = 1;
    private String sdPath;//SD卡的路径
    private String picPath;
    //调用系统相册-选择图片
    private static final int IMAGE = 1;
    private int sl = 0;

    private Button sure;
    private Button returns;

    private EditText number;
    private ImageView qr;
    private ImageView tmv;
    private ImageView tph;
    private VideoView mvplay;
    private Button type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inspection_question);
        setTitle("异常记录");
        //获取摄像头权限
        getCameraPermission();
        //ZXingLibrary初始化
        ZXingLibrary.initDisplayOpinion(this);
        sure = (Button)findViewById(R.id.sure);
        returns = (Button)findViewById(R.id.returns);
        tph = (ImageView)findViewById(R.id.tph);
        number = (EditText) findViewById(R.id.number);
        qr = (ImageView) findViewById(R.id.qr);
        tmv = (ImageView) findViewById(R.id.tmv);
        mvplay = (VideoView) findViewById(R.id.mvplay);
        type = (Button) findViewById(R.id.type);

        qr.setOnClickListener(new ImageView.OnClickListener(){
            public void onClick(View v){
                sl = 3;
                Intent intent = new Intent(InspectionQuestion.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        type.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                showDialog2();
                setColor();
            }
        });

        tph.setOnClickListener(new ImageView.OnClickListener(){
            public void onClick(View v){
                showDialog();
            }
        });

        tmv.setOnClickListener(new ImageView.OnClickListener(){
            public void onClick(View v){
                sl = 4;
                Intent intent = new Intent();
                intent.setAction("android.media.action.VIDEO_CAPTURE");
                intent.addCategory("android.intent.category.DEFAULT");
                File file = new File(FILE_PATH);
                if(file.exists()){
                    file.delete();
                }
                Uri uri = Uri.fromFile(file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 0);
            }
        });

        sure.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                finish();
            }
        });

        returns.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                finish();
            }
        });

        sdPath = Environment.getExternalStorageDirectory().getPath();
        picPath = sdPath + "/" + "temp.png";
        Log.e("sdPath1",sdPath);
    }

    public void setColor(){
        type.setTextColor(this.getResources().getColor(R.color.negativeTextColor));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(sl == 1){
            if (resultCode == RESULT_OK) {
                if (requestCode == REQUEST_THUMBNAIL) {//对应第一种方法
                    /**
                     * 通过这种方法取出的拍摄会默认压缩，因为如果相机的像素比较高拍摄出来的图会比较高清，
                     * 如果图太大会造成内存溢出（OOM），因此此种方法会默认给图片尽心压缩
                     */
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    tph.setImageBitmap(bitmap);
                }
            }
        }else if(sl == 2){
            //获取图片路径
            if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                String imagePath = c.getString(columnIndex);
                showImage(imagePath);
                c.close();
            }
        }else if(sl == 3){
            if (requestCode == REQUEST_CODE) {
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String result = bundle.getString(CodeUtils.RESULT_STRING);
                        number.setText(result);//解析结果显示在TextView
                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        Toast.makeText(InspectionQuestion.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }else{
            tmv.setVisibility(View.GONE);
            mvplay.setVisibility(View.VISIBLE);
            MediaController controller = new MediaController(this);
            this.mvplay.setMediaController(controller);
//下面android:resource://是固定的，org.dengzh是我的包名，不是.java文件package名称，R.raw.movie_1是id名称
            mvplay.setVideoURI(Uri.parse(FILE_PATH));
        }
    }

    //加载图片
    private void showImage(String imaePath){
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        ((ImageView)findViewById(R.id.tph)).setImageBitmap(bm);
    }

    public void getCameraPermission()
    {
        if (Build.VERSION.SDK_INT>22){
            if (ContextCompat.checkSelfPermission(InspectionQuestion.this,
                    android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                //先判断有没有权限 ，没有就在这里进行权限的申请
                ActivityCompat.requestPermissions(InspectionQuestion.this,
                        new String[]{android.Manifest.permission.CAMERA},2);
            }else {
                //说明已经获取到摄像头权限了 想干嘛干嘛
            }
        }else {
            //这个说明系统版本在6.0之下，不需要动态获取权限。
        }
    }

    private void showDialog2(){
        final String[] items = {"设备损坏","设备隐患","设备丢失"};
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int index) {
                switch (index){
                    case 0:type.setText("设备损坏");
                        break;
                    case 1: type.setText("设备隐患");
                        break;
                    case 2: type.setText("设备丢失");
                        break;
                    default:break;
                }
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }

    private void showDialog(){
        final String[] items = {"拍摄","从相册选择"};
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int index) {
                switch (index){
                    case 0:sl = 1;
                        Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 启动相机
                        startActivityForResult(intent1, REQUEST_THUMBNAIL);
                        break;
                    case 1: sl = 2;
                        //调用相册
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, IMAGE);
                        break;
                }
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }
}